package com.shiro.demo.Config;

import com.shiro.demo.Model.Permission;
import com.shiro.demo.Model.Role;
import com.shiro.demo.Model.User;
import com.shiro.demo.Service.UserService;
import com.sun.corba.se.impl.oa.toa.TOA;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Csea
 * @title
 * @date 2019/5/7 13:20
 */
@Slf4j
public class AuthReaml extends AuthorizingRealm {
    @Autowired
    private UserService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("第一批："+principals.getPrimaryPrincipal());
//        User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();
        User user = (User) principals.getPrimaryPrincipal();
        List<String> permissionList = new ArrayList<>();
        List<String> roleNameList = new ArrayList<>();
        Set<Role> roleSet = user.getRoles();
        if (CollectionUtils.isNotEmpty(roleSet)) {
            for (Role role : roleSet) {
                Set<Permission> permissionSet = role.getPermissions();
                if (CollectionUtils.isNotEmpty(permissionSet)) {
                    for (Permission permission : permissionSet) {
                        permissionList.add(permission.getName());
                    }
                    roleNameList.add(role.getRname());
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(permissionList);
        info.addRoles(roleNameList);
        System.out.println("权限列表：" + permissionList);
        System.out.println("角色列表：" + roleNameList);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
////        String username = usernamePasswordToken.getUsername();
////        User user = service.findByUsername(username);
////        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());
        String username = (String) token.getPrincipal();
        User user = service.findByUsername(username);
        if (user == null) {
            System.out.println("账号不存在");
            return null;
        }
        System.out.println("获取到的账号是：" + username + "获取到的密码是：" + user.getPassword() + "第三个参数是：" + getName());
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
